import {
  ErrorRequestHandler,
  Request,
  Response,
  NextFunction as NF,
  response,
  NextFunction,
} from "express";
import { tokenTime } from "../../config";
import { findtitlelimit, userinfo, type asyncPromise } from "../../interface";
import CommentSer from "../../services/CommentSer";
import { routerHandleReturn } from "../../type";
import { info, err } from "../middleware/infoerr";

export default {
  async getall(req: Request, res: Response, next: NextFunction) {
    try {
      const data = await CommentSer.getall();
      info(res, "ok", data);
    } catch (error) {
      next(error);
    }
  },
  async submit(req: Request, res: Response, next: NextFunction) {
    try {
      if (!req.body.content || !req.body.createdTime)
        return err(res, "参数错误", req.body);
      const data = {
        content: req.body.content,
        createdTime: req.body.createdTime,
        name: req.query.name,
        imgUrl: req.query.imgUrl,
        zan: 0,
        cai: 0,
      };
      const result = await CommentSer.submit(data);
      if (!result) return err(res, "错误", result);
      return info(res, "ok", result);
    } catch (error) {
      next(error);
    }
  },
  async update(req: Request, res: Response, next: NextFunction) {
    try {
      if (+req.body.id)
        if (req.body.zan || req.body.cai) {
          const ispk = await CommentSer.findpk(+req.body.id);
          if (!ispk) return err(res, "找不到对应id值", req.body);
          if (req.body.zan === "zan" && !req.body.cai) {
            const data = {
              zan: +ispk.zan + 1,
            };
            const result = await CommentSer.update(data, +req.body.id);
            if (result) return info(res, "ok");
            return err(res, "点赞失败");
          }
          if (!req.body.zan && req.body.cai === "cai") {
            const data = {
              cai: +ispk.cai + 1,
            };
            const result = await CommentSer.update(data, +req.body.id);
            if (result) return info(res, "ok");
            return err(res, "踩失败");
          }
          return err(res, "点在和踩只能有一个");
        }
      err(res, "参数有误", req.body);
    } catch (error) {
      next(error);
    }
  },
};
